package cn.eoe.example.my_texttospeech;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.widget.Toast;

import java.util.Locale;

/**
 * Created by jiang at 2020/8/20
 */
class TTSHelper {
    private Context context;
    private TextToSpeech tts;

    public TTSHelper(Context context) {
        this.context = context;
        prepare();
    }
    private void prepare() {
        tts = new TextToSpeech(context, new listener());
    }

    private class listener implements TextToSpeech.OnInitListener {

        @Override
        public void onInit(int status) {
            if (status == TextToSpeech.SUCCESS) {
                //设置播放语言
                int result = tts.setLanguage(Locale.CHINA);
                if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                    Toast.makeText(context, "不支持", Toast.LENGTH_SHORT).show();
                    Log.d("TextToSpeech", "不支持");
                } else if (result == TextToSpeech.LANG_AVAILABLE) {
                    //初始化成功之后才可以播放文字
                    //否则会提示“speak failed: not bound to tts engine
                    //TextToSpeech.QUEUE_ADD会将加入队列的待播报文字按顺序播放
                    //TextToSpeech.QUEUE_FLUSH会替换原有文字
                    // tts.speak("需要转化的文字", TextToSpeech.QUEUE_ADD, null);
                    //
                    Log.d("TextToSpeech", "初始化成功");
                }

            } else {
                Log.e("TAG", "初始化失败");
            }

        }
    }

    public void speakOut(String text) {
        tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
    }

    public void stopTTS() {
        if (tts != null) {
            tts.shutdown();
            tts.stop();
            tts = null;
        }
    }
}
